package cn.edu.cqu.fredyvia.forum.controller;

import cn.edu.cqu.fredyvia.forum.entity.User;
import cn.edu.cqu.fredyvia.forum.service.IUserInfoService;
import cn.edu.cqu.fredyvia.forum.service.IUserService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2021-07-08
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IUserInfoService userInfoService;

    @PostMapping("/exist")
    @ResponseBody
    public AjaxResult checkUsername(String username) {
        return toAjax(userService.getUserByUsername(username) == null);
    }

    @PostMapping("/register")
    @ResponseBody
    @Log(title = "register", businessType = BusinessType.INSERT)
    public AjaxResult register(@RequestParam User user) {
        try {
//            User user = Map2ObjectUtils.mapToBean(map,User.class);
//            UserInfo userInfo =  Map2ObjectUtils.mapToBean(map,UserInfo.class);
//            User user = JSON.parseObject(JSON.toJSONString(map), User.class);
            log.info(user.toString());
            return AjaxResult.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("用户已存在");
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, String code) {
        log.info(username+" | "+password+" | "+code);
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        if (!CaptchaUtil.ver(code, request)) {
//            CaptchaUtil.clear(request);  // 清除session中的验证码
//            return AjaxResult.error("验证码不正确");
//        }
        log.info("验证码正确");
        try {
            UsernamePasswordAuthenticationToken token =
                    new UsernamePasswordAuthenticationToken(username, password);
            Authentication authentication = authenticationManager.authenticate(token);
//            System.out.println(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return AjaxResult.success("登陆成功");
        } catch (AuthenticationException authenticationException) {
            return AjaxResult.error("登录失败");
        }
    }

//    @GetMapping
//    @ResponseBody
//    public AjaxResult logout() {
////        SecurityContextHolder.
////        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        List<Object> o= sessionRegistry.getAllPrincipals();
//        //退出成功后删除当前用户session
//        for (Object principal : o) {
//            if (principal instanceof User) {
//                final User loggedUser = (User) principal;
//                if (authentication.getName().equals(loggedUser.getUsername())) {
//                    List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);
//                    if (null != sessionsInfo && sessionsInfo.size() > 0) {
//                        for (SessionInformation sessionInformation : sessionsInfo) {
//                            sessionInformation.expireNow();
//                        }
//                    }
//                }
//            }
//        }
//
//        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
//        httpServletResponse.setContentType("application/json;charset=utf-8");
//        httpServletResponse.getWriter().write("退出成功，请重新登录");
//
//        return AjaxResult.success();
//    }
}
